#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include "aht10.h"
#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

#define LED_PIN PIN_LED_R
#define PIN_LED_B GET_PIN(F, 11) // PF11 : LED_B --> LED
#define PIN_LED_R GET_PIN(F, 12) // PF12 : LED_R --> LED
/* 配置蜂鸣器引脚 */
#define PIN_BEEP        GET_PIN(B, 0)      // PA1:  BEEP         --> BEEP (PB1)

int main(void)
{
    float humidity, temperature;
    aht10_device_t dev;

    /* 设 置 LED 引 脚 为 输 出 模 式 */
    rt_pin_mode(PIN_LED_R, PIN_MODE_OUTPUT);
    rt_pin_mode(PIN_BEEP, PIN_MODE_OUTPUT);
    rt_pin_write(PIN_LED_R, PIN_HIGH);
    rt_pin_write(PIN_LED_B, PIN_HIGH);
    rt_pin_write(PIN_BEEP,PIN_LOW);

    const char *i2c_bus_name = "i2c3";

    /* 等待传感器正常工作 */
    rt_thread_mdelay(2000);

    dev = aht10_init(i2c_bus_name);
    if (dev == RT_NULL)
    {
        LOG_E(" The sensor initializes failure");
        return 0;
    }

    while (1)
    {
        if(temperature<31.0&&humidity<90.0)
        {
            rt_pin_write(PIN_LED_R, PIN_HIGH);
            rt_pin_write(PIN_LED_B, PIN_LOW);
        }
        if(temperature>=31.0)
        {
           rt_pin_write(PIN_LED_R, PIN_LOW);
           rt_pin_write(PIN_LED_B, PIN_HIGH);
           if(temperature>=33.0)
               rt_pin_write(PIN_BEEP,PIN_HIGH);
           else
               rt_pin_write(PIN_BEEP,PIN_LOW);
        }
        if(humidity>=90.0)
        {
            rt_pin_write(PIN_LED_R, PIN_LOW);
            rt_pin_write(PIN_LED_B, PIN_LOW);
        }

        /* 读取湿度 */
        humidity = aht10_read_humidity(dev);
        LOG_D("humidity   : %d.%d %%", (int)humidity, (int)(humidity * 10) % 10);

        /* 读取温度 */
        temperature = aht10_read_temperature(dev);
        LOG_D("temperature: %d.%d", (int)temperature, (int)(temperature * 10) % 10);
        rt_thread_mdelay(500);
        rt_pin_write(PIN_BEEP,PIN_LOW);
        rt_thread_mdelay(1000);
    }
    return 0;
}
